<?php

namespace App\Manage;

//use Mews\Captcha\Facades\Captcha;
use App\Models\Admin;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Crypt;
use  App\Service\Captcha;
use Illuminate\Support\Facades\Session;


class AccountManage extends Manage
{


    // 验证码验证
    public function check($name = "admin_login")
    {
        // captcha为填写的验证码
        // key生成验证码返回的key
        $opt     = $this->option();
        $captcha = $opt->getData('captcha', null, 'trim');
        $key     = $opt->getData('key', null, 'trim');
        if(empty($captcha)){ // || empty($key)
            //return $this->_returnFail('传递数据有误!!');
            return $this->_returnFail('data_transmission_error');
        }

        // 验证验证码
        /*$is_ok = captcha_api_check($captcha, $key);
        if(!$is_ok){
            //return $this->_returnFail('验证码有误!!');
            return $this->_returnFail('verification_code_is_wrong');
        }*/
        // 验证验证码
        $code  = Session::get($name);
        $is_ok = $code == $captcha;
        if(!$is_ok){
            //return $this->_returnFail('验证码有误!!');
            return $this->_returnFail('verification_code_is_wrong');
        }

        return true;
    }

    // 验证码
    // 参考文档 https://blog.csdn.net/qq78442761/article/details/125796778
    public function captcha2()
    {
        // 展示验证码
        $image = Captcha::create("default", true);

        // 获取验证码的img作为图片显示
        return $image;
    }

    // 用户信息
    public function info($uid)
    {
        $model = new Admin();
        $info  = $model->oneFind(['id' => $uid]);
        if($info === false){
            return $this->_returnFail('user_has_no_exist');
            //return $this->_returnFail('用户不存在'.$uid);
        }

        // 目录
        $menus = $model->getAllMenu();
        if(!$menus){
            return $this->_returnFail(__('No background menu, please contact super administrator!'));
        }

        // 站点配置
        $lang = $this->option()->getLang() == 'en' ? 'en' : 'zh';
        $site = Config::get('site.'.$lang);

        return [
            'info'       => $info,
            'menus'      => $menus,
            'siteConfig' => [
                'siteName' => 'Little Rascal',
                'version'  => '1.02.2',
                'cdnUrl'   => 'http://',
                'apiUrl'   => 'http:',
                'site'     => $site,
                'upload'   => [
                    'allowedMimeTypes' => [],
                    'allowedSuffixes'  => "jpg,png,bmp,jpeg,gif,webp,zip,rar,wav,mp4,mp3",
                    'maxSize'          => 10485760,
                    'mode'             => "local",
                    'saveName'         => "/storage/{topic}/{year}{mon}{day}/{fileName}{fileSha1}{.suffix}",
                ],
            ],
            'terminal'   => [
                'phpDevelopmentServer' => str_contains($_SERVER['SERVER_SOFTWARE'], 'Development Server'),
                'npmPackageManager'    => 'pnpm',
            ],
        ];
    }

    // 验证码
    public function captcha($name = "admin_login")
    {
        $image = (new Captcha())->makeCode($name);

        return $image;
    }

    // 修改
    public function edit($myUser, $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt  = $this->option();
        $data = [
            //'username' => $opt->getData('username', null, 'trim'),
            //'role'     => $opt->getData('role', null, 'trim'),
            'nickname' => $opt->getData('nickname', null, 'trim'),
            'password' => $opt->getData('password', null, 'trim'),
            'mobile'   => $opt->getData('mobile', null, 'trim'),
            //'status'   => $opt->getData('status', 1, 'intval),
        ];


        // 检查唯一性
        $model = new Admin();
        $data  = $model->filterField($data, true);
        if(empty($data)){
            //return $this->_returnFail('不能修改为空！');
            return $this->_returnFail('send_data_to_be_modify');
        }

        // 检查唯一性
        $data = $model->checkUser($data, $myUser['id']);
        if(empty($data)){
            //return $this->_returnFail('不能修改为空！');
            return $this->_returnFail('send_data_to_be_modify');
        }

        // 验证
        $where  = ['id' => $myUser['id']];
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 管理员日志
        if($is_admin_log){
            //$this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }


        return true;
    }

    // 修改密码
    public function password($myUser, $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt  = $this->option();
        $data = ['password' => $opt->getData('password', null, 'trim'),];


        // 检查是否为空
        $model = new Admin();
        $data  = $model->filterField($data, true);
        if(empty($data)){
            //return $this->_returnFail('不能修改为空！');
            return $this->_returnFail('send_data_to_be_modify');
        }


        $data   = $model->checkData($data);
        $where  = ['id' => $myUser['id']];
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 管理员日志
        if($is_admin_log){
            //$this->addAdminLog($myUser['id'], '修改自己的密码', '');
        }

        return true;
    }

    // 登录
    public function login($options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 验证
        $opt      = $this->option();
        $is_build = $opt->getData('is_build', 0, 'intval');  // 是否 buildadmin
        $username = $opt->getData('username', null, 'trim');
        $password = $opt->getData('password', null, 'trim');
        $onlineip = $opt->getIp();

        // 如果没有账户密码 则返回进行验证码验证
        if(empty($username) && empty($password)){
            return ['captcha' => true];
        }

        // TODO 验证验证码


        // 登录操作
        $model = new Admin();
        $user  = $model->login($username, $password);
        if($user === false){
            return $this->_returnFail($model->getError());
        }


        // 管理员日志
        if($is_admin_log){
            //$this->addAdminLog($user['id'], '修改自己的密码', '');
        }


        // 返回
        $info = ['id' => $user['id'], 'username' => $user['username']];
        //$token = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $token = $opt->setToken($info);
        $menu  = $model->getUserMenu($user['id'], $user['role']);  // 权限整理
        // 整理返回
        unset($user['role']);
        $user['uid'] = $user['id'];
        // 整理返回
        if($is_build){
            // 'last_login_time' => $user['last_time'],
            $result = ['userInfo' => ['avatar' => '', 'id' => $user['id'], 'nickname' => $user['nickname'], 'refresh_token' => '', 'token' => $token, 'username' => $user['username'],]];
        } else{
            $result = ['token' => $token, 'user' => $user, 'menu' => $menu,];
        }

        return $result;
    }

    // 生成token
    public function token()
    {
        $opt = $this->option();
        $uid = $opt->getData('uid', 0, 'intval');

        $model = new Admin();
        $field = ['id', 'username', 'status', 'nickname', 'mobile', 'role'];
        $user  = $model->where(['id' => $uid])->select($field)->first(); // ->recycle()
        if($user === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($user)){
            //return $this->_returnFail('用户不存在！！');
            return $this->_returnFail('user_has_no_exist');
        }
        if($user->status === 0){
            //return $this->_returnFail('用户被禁用！！');
            return $this->_returnFail('user_has_not_exist_or_has_been_disabled');
        }

        $user  = $user->toArray();
        $info  = ['id' => $user->id, 'username' => $user->username, 'ctime' => LARAVEL_TIME,];
        $token = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $menu  = $model->getUserMenu($user['id'], $user['role']);  // 权限整理
        // 整理返回
        $user['uid'] = $user['id'];
        unset($user['role']);
        $result = ['token' => $token, 'user' => $user, 'menu' => $menu,];

        return $result;
    }

}

